# backend\models\intervention_log.py
from datetime import datetime
from backend.infrastructure.database import db
from backend.services.unified_log_service import UnifiedLogAction

class InterventionRecordLog(db.Model):
    __tablename__ = "intervention_record_logs"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    
    # 关联字段
    record_id = db.Column(db.Integer, nullable=False, comment="干预记录ID")
    student_id = db.Column(db.Integer, nullable=False, comment="学生ID")
    
    # 操作信息（统一日志服务标准化）
    action = db.Column(db.String(20), nullable=False, comment="操作类型：CREATE/UPDATE/DELETE/RESTORE")
    operator = db.Column(db.String(50), nullable=True, comment="操作员")
    ip_address = db.Column(db.String(50), nullable=True, comment="操作IP地址")  # 字段名标准化
    operator_type = db.Column(db.String(20), nullable=True, comment="操作员类型：医生/护士/管理员")
    operation_time = db.Column(db.DateTime, nullable=True, comment="操作时间")  # 新增字段
    user_agent = db.Column(db.String(200), nullable=True, comment="用户代理")  # 新增字段
    
    # 操作详情
    operation_desc = db.Column(db.String(100), nullable=True, comment="操作详情描述")  # 字段名标准化
    old_content = db.Column(db.Text, nullable=True, comment="修改前内容")
    new_content = db.Column(db.Text, nullable=True, comment="修改后内容")
    
    # 家庭干预相关字段
    is_home_intervention = db.Column(db.Boolean, default=False, comment="是否家庭干预操作")
    home_operator = db.Column(db.String(50), nullable=True, comment="家庭操作员（家长姓名）")
    upload_source = db.Column(db.String(20), nullable=True, comment="上传来源：PC端/小程序")
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    
    # 索引
    __table_args__ = (
        db.Index('ix_record_student', 'record_id', 'student_id'),
        db.Index('ix_action_time', 'action', 'created_at'),
        db.Index('ix_operator', 'operator'),
        {'comment': '干预记录操作日志表'}
    )

    def to_dict(self):
        return {
            "id": self.id,
            "record_id": self.record_id,
            "student_id": self.student_id,
            "action": self.action,
            "operator": self.operator,
            "ip_address": self.ip_address,  # 字段名更新
            "operator_type": self.operator_type,
            "operation_time": self.operation_time.isoformat() if self.operation_time else None,  # 新增字段
            "user_agent": self.user_agent,  # 新增字段
            "operation_desc": self.operation_desc,  # 字段名更新
            "old_content": self.old_content,
            "new_content": self.new_content,
            "is_home_intervention": self.is_home_intervention,
            "home_operator": self.home_operator,
            "upload_source": self.upload_source,
            "created_at": self.created_at.isoformat() if self.created_at else None,
        }
        
    def get_operation_summary(self):
        """获取操作摘要信息"""
        if self.is_home_intervention:
            return f"家庭干预操作 - {self.home_operator} - {self.upload_source}"
        else:
            return f"医院操作 - {self.operator} - {self.operator_type}"
    
    # 🔧 新增：统一日志服务标准方法
    @classmethod
    def log_create(cls, record, operator='系统', ip_address=None, user_agent=None):
        """创建日志记录"""
        try:
            import json
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action=UnifiedLogAction.CREATE.value,
                operator=operator,
                ip_address=ip_address,
                operator_type=getattr(record, 'operator_type', None),  # 处理额外字段
                operation_time=datetime.now(),
                user_agent=user_agent,
                operation_desc=f'创建干预记录 - 干预日期: {record.intervention_date}',
                old_content=None,
                new_content=json.dumps(record.to_dict(), ensure_ascii=False, default=str),
                is_home_intervention=getattr(record, 'is_home_intervention', False),  # 处理额外字段
                home_operator=getattr(record, 'home_operator', None),  # 处理额外字段
                upload_source=getattr(record, 'upload_source', 'PC端')  # 处理额外字段
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"创建日志失败: {e}")
            return None
    
    @classmethod
    def log_update(cls, record, old_data, operator='系统', ip_address=None, user_agent=None):
        """更新日志记录"""
        try:
            import json
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action=UnifiedLogAction.UPDATE.value,
                operator=operator,
                ip_address=ip_address,
                operator_type=getattr(record, 'operator_type', None),  # 处理额外字段
                operation_time=datetime.now(),
                user_agent=user_agent,
                operation_desc=f'更新干预记录 - 干预日期: {record.intervention_date}',
                old_content=json.dumps(old_data, ensure_ascii=False, default=str),
                new_content=json.dumps(record.to_dict(), ensure_ascii=False, default=str),
                is_home_intervention=getattr(record, 'is_home_intervention', False),  # 处理额外字段
                home_operator=getattr(record, 'home_operator', None),  # 处理额外字段
                upload_source=getattr(record, 'upload_source', 'PC端')  # 处理额外字段
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"更新日志失败: {e}")
            return None
    
    @classmethod
    def log_delete(cls, record, operator='系统', ip_address=None, user_agent=None):
        """删除日志记录"""
        try:
            import json
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action=UnifiedLogAction.DELETE.value,
                operator=operator,
                ip_address=ip_address,
                operator_type=getattr(record, 'operator_type', None),  # 处理额外字段
                operation_time=datetime.now(),
                user_agent=user_agent,
                operation_desc=f'删除干预记录 - 干预日期: {record.intervention_date}',
                old_content=json.dumps(record.to_dict(), ensure_ascii=False, default=str),
                new_content=None,
                is_home_intervention=getattr(record, 'is_home_intervention', False),  # 处理额外字段
                home_operator=getattr(record, 'home_operator', None),  # 处理额外字段
                upload_source=getattr(record, 'upload_source', 'PC端')  # 处理额外字段
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"删除日志失败: {e}")
            return None
    
    @classmethod
    def log_restore(cls, record_id, student_id, old_data, restored_data, operator='系统', ip_address=None, user_agent=None):
        """恢复日志记录"""
        try:
            import json
            log = cls(
                record_id=record_id,
                student_id=student_id,
                action=UnifiedLogAction.RESTORE.value,
                operator=operator,
                ip_address=ip_address,
                operator_type=restored_data.get('operator_type', None) if isinstance(restored_data, dict) else None,  # 处理额外字段
                operation_time=datetime.now(),
                user_agent=user_agent,
                operation_desc=f"恢复干预记录 - 记录ID: {record_id}",
                old_content=json.dumps(old_data, ensure_ascii=False, default=str),
                new_content=json.dumps(restored_data, ensure_ascii=False, default=str),
                is_home_intervention=restored_data.get('is_home_intervention', False) if isinstance(restored_data, dict) else False,  # 处理额外字段
                home_operator=restored_data.get('home_operator', None) if isinstance(restored_data, dict) else None,  # 处理额外字段
                upload_source=restored_data.get('upload_source', 'PC端') if isinstance(restored_data, dict) else 'PC端'  # 处理额外字段
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"恢复日志失败: {e}")
            return None
